package com.geniusk.mqtt;

import io.netty.channel.Channel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 设备ID和channel的关联关系处理
 */
@Slf4j
public class TopicChannelSession {

	@Getter
	private static final ConcurrentHashMap<String, List<Channel>> topicChannelSession = new ConcurrentHashMap<>();

	/**
	 * 信道主题关系
	 */
	private static final ConcurrentHashMap<String, String> topicChannelRelation = new ConcurrentHashMap<>();

	/**
	 * 建立主题信道关系
	 * @param topicName 主题名称
	 * @param channel 信道
	 */
	public static void setChannel(String topicName, Channel channel) {
		List<Channel> channelList = topicChannelSession.get(topicName);
		if(channelList == null || channelList.isEmpty()){
			channelList = new ArrayList<>();
		}
		channelList.add(channel);
		topicChannelSession.put(topicName, channelList);
		topicChannelRelation.put(channel.id().asLongText(),topicName);
	}

	/**
	 * 移除主题信道关系
	 * @param topicName 主题名称
	 * @param channelId 信道ID
	 */
	public static void removeChannel(String topicName, String channelId){
		List<Channel> channelList = topicChannelSession.get(topicName);
		if (channelList == null || channelList.isEmpty()) {
			return;
		}
		channelList.removeIf(channel -> channel.id().asLongText().equals(channelId));
		if(channelList.isEmpty()){
			topicChannelSession.remove(topicName);
		}else {
			topicChannelSession.put(topicName, channelList);
		}
		topicChannelRelation.remove(channelId);
	}

	/**
	 * 根据主题ID获取信道列表
	 * @param topicName 主题名称
	 * @return 信道列表
	 */
	public static List<Channel> getChannelListByTopicName(String topicName) {
		return topicChannelSession.get(topicName);
	}

	/**
	 * 根据信道ID获取对应主题ID
	 * @param channelId 信道ID
	 * @return 主题ID
	 */
	public static String getTopicNameByChannelId(String channelId){
		return topicChannelRelation.get(channelId);
	}

	/**
	 * 打印主题信道关系
	 */
	public static void output() {
		for (HashMap.Entry<String, List<Channel>> entry : topicChannelSession.entrySet()) {
			for(Channel channel : entry.getValue()){
				log.info("topicName:{}, channelId:{}", entry.getKey(), channel.id().asLongText());
			}
		}
	}

}
